package com.qdhh.enrollment.controller.miniapp;

import cn.dev33.satoken.stp.StpUtil;
import com.qdhh.enrollment.common.Result;
import com.qdhh.enrollment.model.Student;
import com.qdhh.enrollment.model.StudentProfile;
import com.qdhh.enrollment.service.StudentProfileService;
import com.qdhh.enrollment.service.StudentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Tag(name = "小程序-档案管理", description = "小程序学生档案查询和更新接口")
@RestController
@RequestMapping("/api/miniapp/profile")
public class MiniappProfileController {

    private static final Logger log = LoggerFactory.getLogger(MiniappProfileController.class);

    private final StudentProfileService studentProfileService;
    private final StudentService studentService;

    public MiniappProfileController(StudentProfileService studentProfileService, StudentService studentService) {
        this.studentProfileService = studentProfileService;
        this.studentService = studentService;
    }

    @Operation(summary = "查询个人档案", description = "获取当前登录学生的档案信息，需要登录认证")
    @GetMapping
    public Result<StudentProfile> me() {
        // 使用 Sa-Token 获取当前登录学生ID
        String studentId = StpUtil.getLoginIdAsString();
        log.debug("Resolved studentId for GET /api/miniapp/profile: {}", studentId);
        try {
            // 获取当前学生信息，获取学号
            Student student = studentService.getCurrentStudent();
            if (student == null || !StringUtils.hasText(student.getStudentNo())) {
                return Result.success("OK", null);
            }
            
            // 根据学号查询 student_profiles 表
            StudentProfile profile = studentProfileService.getByStudentNo(student.getStudentNo());
            if (profile == null) {
                return Result.success("OK", null);
            }
            return Result.success("OK", profile);
        } catch (Exception ex) {
            log.warn("Failed to fetch profile for {}: {}", studentId, ex.getMessage());
            return Result.success("OK", null);
        }
    }

    @Operation(summary = "查询档案审核状态", description = "查询当前学生档案的审核状态，需要登录认证")
    @GetMapping("/status")
    public Result<Map<String, Object>> getStatus() {
        String studentId = StpUtil.getLoginIdAsString();
        try {
            Student student = studentService.getCurrentStudent();
            if (student == null) {
                return Result.failure(400, "用户不存在");
            }
            
            // 根据当前设计，档案无需审核流程，直接返回已通过状态
            Map<String, Object> status = new HashMap<>();
            status.put("status", "APPROVED"); // 直接通过
            status.put("reason", "");
            return Result.success("OK", status);
        } catch (Exception ex) {
            log.warn("Failed to fetch status for {}: {}", studentId, ex.getMessage());
            Map<String, Object> status = new HashMap<>();
            status.put("status", "DRAFT");
            status.put("reason", "");
            return Result.success("OK", status);
        }
    }

    @Operation(summary = "提交审核", description = "提交档案审核，需要登录认证。根据当前设计，档案无需审核流程")
    @PostMapping("/submit")
    public Result<Void> submitReview() {
        String studentId = StpUtil.getLoginIdAsString();
        log.debug("Submit review for student: {}", studentId);
        // 根据当前设计，档案无需审核流程，直接返回成功
        return Result.success("提交成功", null);
    }

    @Operation(summary = "提交/更新档案", description = "提交或更新学生档案信息，需要登录认证。如果学号变更会自动触发身份认证")
    @PostMapping("/register")
    public Result<ProfileResponse> register(@RequestBody ProfileRequest body) {
        // 使用 Sa-Token 获取当前登录学生ID
        String studentId = StpUtil.getLoginIdAsString();
        log.debug("Resolved studentId for POST /api/miniapp/profile/register: {}", studentId);
        try {
            // 获取当前学生信息
            Student student = studentService.getCurrentStudent();
            if (student == null) {
                return Result.failure(400, "用户不存在");
            }
            
            // 学号必须提供
            String studentNo = body != null ? body.getStudentNo() : null;
            if (!StringUtils.hasText(studentNo)) {
                return Result.failure(400, "学号不能为空");
            }
            
            // 如果学生还没有学号，先更新学号（会触发身份认证）
            String currentStudentNo = student.getStudentNo();
            if (!StringUtils.hasText(currentStudentNo)) {
                studentService.updateStudentNo(studentId, studentNo);
            } else if (!Objects.equals(studentNo, currentStudentNo)) {
                // 如果学号不一致，更新学号（会触发身份认证）
                studentService.updateStudentNo(studentId, studentNo);
            }
            
            // 构建 StudentProfile 对象
            StudentProfile toPatch = StudentProfile.builder()
                .name(body != null ? body.getRealName() : null)
                .studentNo(studentNo)
                .phone(body != null ? body.getPhone() : null)
                .college(body != null ? body.getCollege() : null)
                .major(body != null ? body.getMajor() : null)
                .className(body != null ? body.getClassName() : null)
                .email(body != null ? body.getEmail() : null)
                .build();
            
            // 使用学号更新或插入 student_profiles 表
            StudentProfile saved = studentProfileService.upsertByStudentNo(studentNo, toPatch);
            
            ProfileResponse response = new ProfileResponse();
            response.setStudentNo(saved != null ? saved.getStudentNo() : studentNo);
            return Result.success("OK", response);
        } catch (Exception ex) {
            log.error("Failed to upsert profile for {}: {}", studentId, ex.getMessage());
            return Result.failure(500, "操作失败: " + ex.getMessage());
        }
    }

    public static class ProfileRequest {
        private String realName; // 对应 StudentProfile.name
        private String studentNo; // 学号（必需）
        private String phone; // 手机号
        private String college; // 学院
        private String major; // 专业
        private String className; // 班级
        private String email; // 邮箱

        public String getRealName() {
            return realName;
        }

        public void setRealName(String realName) {
            this.realName = realName;
        }

        public String getStudentNo() {
            return studentNo;
        }

        public void setStudentNo(String studentNo) {
            this.studentNo = studentNo;
        }

        public String getPhone() {
            return phone;
        }

        public void setPhone(String phone) {
            this.phone = phone;
        }

        public String getCollege() {
            return college;
        }

        public void setCollege(String college) {
            this.college = college;
        }

        public String getMajor() {
            return major;
        }

        public void setMajor(String major) {
            this.major = major;
        }

        public String getClassName() {
            return className;
        }

        public void setClassName(String className) {
            this.className = className;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }
    }

    public static class ProfileResponse {
        private String studentNo; // 返回学号

        public String getStudentNo() {
            return studentNo;
        }

        public void setStudentNo(String studentNo) {
            this.studentNo = studentNo;
        }
    }
}

